package com.bskj.kuaifu.service.template;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.WechatTemplateMsg;
import com.bskj.common.bean.model.WxTemplate;
import com.bskj.common.utils.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by mocaijin on 05/02/2018.
 */
public class TemplateMessageUtil {

    public static String sendTemplateMessage(String appId, String openId,Map<String,Object> paramMap, WxTemplate wxTemplate) throws Exception {
        if (wxTemplate == null) {
            return "";
        }
        Integer userId = (Integer)paramMap.get("userId");
        TemplateMessageAction templateMessageAction = SpringContextHolder.getBean(wxTemplate.getBeanName());
        WechatTemplateMsg wechatTemplateMsg = templateMessageAction.processMessage(paramMap);

        if (StringUtils.isBank(wechatTemplateMsg.getTemplate_id())) {
            wechatTemplateMsg.setTemplate_id(wxTemplate.getTemplateId());
        }

        wechatTemplateMsg.setTouser(openId);
        if (!StringUtils.isBank(wxTemplate.getUrl())) {
            JSONObject uriParams = new JSONObject();
            uriParams.put("uri", wxTemplate.getUrl());
            uriParams.put("userId", userId);
            uriParams.put("appId", appId);
            uriParams.put("openId", openId);
            String templateLinkUrl = Global.getConfig("KUAIFU_ACTION_URL") + EncryptUtil.encrypt(uriParams.toJSONString());
            wechatTemplateMsg.setUrl(templateLinkUrl);
        }
        String jsonData = JSONObject.toJSONString(wechatTemplateMsg);
        LogUtils.debug("jsonData:" + jsonData);
        String WX_SEND_TEMPLATE_URL = Global.getConfig("WX_SEND_TEMPLATE_URL");
        LogUtils.debug("WX_SEND_TEMPLATE_URL:" + WX_SEND_TEMPLATE_URL);
        Map<String, Object> params = new HashMap<>();
        params.put("jsonData", jsonData);
        params.put("appId", appId);
        return HttpRequestUtil.httpClientGet(WX_SEND_TEMPLATE_URL, params);
    }
}
